import {
  Component,
  OnInit,
  Input,
  Output,
  EventEmitter,
  TemplateRef,
  ViewChild, ElementRef
} from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material';
import { get } from 'lodash';
import { ZoneService } from 'app/modules/zone/services/zone.service';
import { Zone } from 'app/modules/zone/services/zone.service';

import { MySelection } from 'app/modules/base/selection';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { ReplaySubject, Subject } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'm-zone-select-input',
  templateUrl: './zone-select-input.component.html',
  styleUrls: ['./zone-select-input.component.scss'],
  providers: [
    {
      multi: true,
      provide: NG_VALUE_ACCESSOR,
      useExisting: ZoneSelectInputComponent,
    },
  ],
})
export class ZoneSelectInputComponent implements OnInit, ControlValueAccessor {
  constructor(
    private dialog: MatDialog,
    private zoneService: ZoneService,
    public http: HttpClient,
  ) {}
  @ViewChild('selectZoneDialogRef') template: TemplateRef<any>;
  @ViewChild('body') body: ElementRef;
  @Input() disabled = false;
  
  @Input() hideRoot = false;
  @Input() selection = new MySelection<Zone>('id', [], false);

  data;
  zoneTree$: Promise<any>;

  selectDialog: MatDialogRef<TemplateRef<any>>;
  zones$ = new ReplaySubject<Zone[]>(1);
  touch$ = new Subject();

  ngOnInit() {
    this.http.get('api/admin/batch_areas',{params:{limit:'50'}}).subscribe((res: any) => {
      this.data = res.message

    });
  }

  roll(e){
    this.body.nativeElement.scrollTop = e
  }

  log(e){
    this.selection.selected = e
  }

  public open(selected) {
    if (this.disabled) {
      return;
    }
    // 给管理区域 回传到当前组建和当前数据 结合 。构建勾选展示数据
    let selectedValues = (selected||[]).map(item=> item.id)
    this.data = this.data.map(item=>{
      item.checked = selectedValues.includes(item.area_id) || selectedValues.includes(item.id)
      return item
    })
    this.touch$.next();
    this.zoneTree$ = this.zoneService.tree().then((data) => {
      if (this.hideRoot && get(data, [0, 'id']) === 0) {
        return data[0].children;
      }
      return data;
    });
    this.selectDialog = this.dialog.open(this.template);
  }

  cancel() {
    this.selectDialog.close();
    this.selection.clear();
    this.zones$.next([]);

  }
  selected() {
    /**
 * 解决消息管理下发消息，点击选择区域按钮，弹出的树组件，在非一级节点点击后按钮内容为空的问题
 */
    this.selectDialog.close()
    // this.zones$.next(this.selection.selected['flat']());
    let obj=this.selection.selected['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']()['flat']();
    // debugger
    this.zones$.next(obj);
    this.zoneService.dataZones$.next(this.data)

  }

  // ControlValueAccessor
  writeValue(arr: Zone[] = []): void {
    if (arr) {
      this.selection.select(...arr);
    } else {
      this.selection.clear();
    }
  }
  registerOnChange(fn: any): void {
    this.zones$.subscribe(fn);
  }
  registerOnTouched(fn: any): void {
    this.touch$.subscribe(fn);
  }
  setDisabledState?(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}
